<?php

namespace app\models;

use Yii;
use yii\helpers\ArrayHelper;
use app\models\UserLogin;
use yii\helpers\Url;
/**
 * This is the model class for table "{{%menu}}".
 *
 * @property int $id
 * @property string $title
 * @property int $pid
 * @property string $icon
 * @property int $sort
 * @property string $module
 * @property string $controller
 * @property string $module_uuid
 * @property string $module_action
 * @property string $action
 * @property int $status
 * @property int $hide
 */
class Menu extends \yii\db\ActiveRecord
{   
    public static $tmp_fields = [ // 数据库字段对应
        'id'            => 'id', // ID
        'sort'          => 'sort', // ID
        'label'         => 'title', // 名称
        // 'pid'           => 'pid', // 父菜单
        // 'module'        => 'module', // 模块
        'controller'    => 'controller', // 控制器
        'action'        => 'action', // 方法
        'icon'          => 'icon', // icon图标
        'child'         => 'items',
        'module_uuid'   => 'module_uuid',
        'module_action' => 'module_action',
    ];

    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return '{{%menu}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['pid', 'sort', 'status', 'hide'], 'integer'],
            [['title', 'icon', 'module', 'controller', 'module_uuid', 'module_action', 'action'], 'string', 'max' => 255],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', 'ID'),
            'title' => Yii::t('app', '名称'),
            'pid' => Yii::t('app', 'Pid'),
            'icon' => Yii::t('app', 'Icon'),
            'sort' => Yii::t('app', '排序'),
            // 'module' => Yii::t('app', 'Module'),
            'controller' => Yii::t('app', 'Controller'),
            'module_uuid' => Yii::t('app', 'Module Uuid'),
            'module_action' => Yii::t('app', 'Module Action'),
            'action' => Yii::t('app', 'Action'),
            'status' => Yii::t('app', 'Status'),
            'hide' => Yii::t('app', 'Hide'),
        ];
    }

    //计算下拉表数据
    public function getDropDownList($res = null){
        //增加顶级分类选项
        $arr=array(
          'new_cat_name'=>'顶级菜单',
          'id'=>0
        );

        $tree = $this->subtree($res,0,1);

        foreach($tree as $k=> $v) {
          $tree[$k]['new_cat_name']=str_repeat('&nbsp;&nbsp;&nbsp;',$v['lev']).$v['title']; //str_repeat — 重复一个字符串
        }
        
        if (!empty($arr)) {
            array_unshift($tree,$arr);
        }

        return ArrayHelper::map($tree,'id','new_cat_name');
    }

    public function subtree($arr,$id=0,$lev=1){
        $subs = array(); // 子孙数组
        foreach($arr as $v) {
          if($v['pid'] == $id) {
            $v['lev'] = $lev;
            $subs[] = $v; // 举例说找到array('id'=>1,'name'=>'安徽','parent'=>0),
            $subs = array_merge($subs,$this->subtree($arr,$v['id'],$lev+1));
          }
        }
        return $subs;
    }

    //删除分类下的所有子分类
    // public static function deleteCategory($id){
    //     self::deleteAll(['pid' => $id]);

    //     self::findOne($id)->delete();
    // }

    /**
     * 获得游戏菜单树
     *
     * @access public
     * @param  string $module
     * @param  int    $hide
     * @param  int    $status
     * @return void
     */
    public function getMenu($hide = null, $status = null) {
        if ($hide !== null) {
            $where['hide'] = $hide;
        }
        if ($hide !== null) {
            $where['status'] = $status;
        }

        return $this::find()->where($where)->all();
    }

    public function formatMenu($menu_data = null){
        if (is_null($menu_data)) {
            $menu_data = $this->getMenu(0, 0);
        }
        $tree_data[] = ['label' => '菜单', 'options' => ['class' => 'header']];
        $_tree_data = self::getTree($menu_data);

        // echo '<pre>';
        // print_r( array_merge($tree_data, $_tree_data));die;

        return array_merge($tree_data, $_tree_data);
    }

    public static function getTree($items = [], $fields = []) {
        if ($fields || !self::$tmp_fields) {
            self::$tmp_fields = array_merge(self::$fields, $fields);
        }

        //权限数据 
        $authModuleAction = UserLogin::getLoginedModel()->authedData;

        $tree                = [];
        $map                 = [];
        // $field_pid           = self::$tmp_fields['pid'];
        $field_icon          = self::$tmp_fields['icon'];
        // $field_module        = self::$tmp_fields['module'];
        $field_controller    = self::$tmp_fields['controller'];
        $field_action        = self::$tmp_fields['action'];
        $field_label         = self::$tmp_fields['label'];
        $field_id            = self::$tmp_fields['id'];
        $field_child         = self::$tmp_fields['child'];
        $field_sort          = self::$tmp_fields['sort'];
        $field_module_uuid   = self::$tmp_fields['module_uuid'];
        $field_module_action = self::$tmp_fields['module_action'];

        foreach ($items as $item) {
            $item = $item->attributes;

            if (isset($item['visible']) && !$item['visible']) {
                continue;
            }

            if ((string) $item['module_uuid'] !== '' && $authModuleAction !== null && (string) $item['controller'] !== '' && !isset($authModuleAction[$item['module_uuid']][$item['module_action']])) {
                continue;
            }

            $actionStr  = ArrayHelper::getValue($item, $field_action);


            if (strpos($actionStr, '?') === false) {
                $actionName = $actionStr;
                $queryArr = [];
            }else{
                $actionName = strstr($actionStr, '?', true);
                parse_str(substr((string) strstr($actionStr, '?'), 1), $queryArr);
            }
            

            $controlStr = ArrayHelper::getValue($item, $field_controller);
            if (empty($actionStr) &&empty($controlStr)) {
                $url = '#';
            }else{
                $url = array_merge($queryArr, ['menu_id' => $item[$field_id]]);
                array_unshift($url, $controlStr . '/' . $actionName);
                // $url = [$controlStr . '/' . $actionName, array_merge($queryArr, ['menu_id' => $item[$field_id]])];
            }

            $map[$item[$field_id]] = array_merge($item, [
                'id'            => $item[$field_id],
                'sort'          => $item[$field_sort],
                'label'         => $item[$field_label],
                'url'           => $url,
                'icon'          => ArrayHelper::getValue($item, $field_icon),
                // 'pid'           => $item[$field_pid],
                'module_uuid'   => isset($item[$field_module_uuid]) ? $item[$field_module_uuid] : null,
                'module_action' => isset($item[$field_module_action]) ? $item[$field_module_action] : null,
            ]);
        }

        foreach ($map as $item) {
            if (isset($map[$item['pid']])) {
                $map[$item['pid']][$field_child][] = &$map[$item['id']];
            } else {
                $tree[] = &$map[$item['id']];
            }
        }

        return self::sortTree($tree);
    }

    /**
     * 树排序
     *
     * @access public
     * @param  void   &$items
     * @return void
     */
    public static function sortTree(&$items, $fields = []) {
        if ($fields || !self::$tmp_fields) {
            self::$tmp_fields = array_merge(self::$fields, $fields);
        }

        $sort_tree = [];
        $id_tree   = [];
        if (!$items) {
            return $items;
        }
        foreach ($items as $key => &$item) {
            if (isset($item[self::$tmp_fields['child']]) && $item[self::$tmp_fields['child']]) {
                self::sortTree($item[self::$tmp_fields['child']]);
            }

            $tree_sort_sort[$key] = $item[self::$tmp_fields['sort']];
            $tree_sort_id[$key]   = $item[self::$tmp_fields['id']];
        }
        array_multisort($tree_sort_sort, SORT_ASC, $tree_sort_id, SORT_DESC, $items);
        return $items;
    }


}
